import java.util.ArrayList;
import java.util.List;

public class Solution1 {
    public int[] dx = {0, 0, 1, -1};
    public int[] dy = {1, -1, 0, 0};
    public int m;
    public int n;

    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        m = heights.length;
        n = heights[0].length;

        boolean[][] pac = new boolean[m][n];
        boolean[][] atl = new boolean[m][n];

        // 1. 先处理太平洋
        for(int j = 0; j < n; j++) {
            dfs(heights, 0, j, pac);
        }
        for(int i = 0; i < m; i++) {
            dfs(heights, i, 0, pac);
        }

        // 2. 处理大西洋
        for(int i = 0; i < m; i++) {
            dfs(heights, i, n - 1, atl);
        }

        for(int j = 0; j < n; j++) {
            dfs(heights, m - 1, j ,atl);
        }

        // 3. 提取结果
        List<List<Integer>> ret = new ArrayList<>();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(pac[i][j] && atl[i][j]) {
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(i);
                    tmp.add(j);
                    ret.add(tmp);
                }
            }
        }
        return ret;
    }

    public void dfs(int[][] heights, int i, int j, boolean[][] visit) {
        visit[i][j] = true;
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && heights[x][y] >= heights[i][j] && !visit[x][y]) {
                dfs(heights, x, y,visit);
            }
        }
    }
}